package com.axapoint.opoc.core.dao;

import java.util.ArrayList;

import org.joda.time.DateTime;
import org.joda.time.Interval;

import com.axapoint.opoc.core.UserException;

public class OrganizationFacade extends AbstractFacade<Organization, Organization.Value, Organization.Bitemporal> {

	public OrganizationFacade(String systemId, String userId) {
		super(systemId, userId, new Organization(), new Organization.Value());
	}
	
	public Unit.Value[] getRootUnits(String uuid, DateTime at) {
		Organization e = getEntity(uuid);
		if (e == null) throw new UserException("Ingen organisation med UUID: " + uuid);
		
		ArrayList<Unit.Value> result = new ArrayList<Unit.Value>();
        for (RootUnitRelation.Value v : e.getRootUnitRelations()) {
        	if (at == null || v.getBitemporal().getValidityInterval().contains(at)) {
        		
        		result.add(v.getUnit().getValues().get(at).getValue());
        	}
        }

		return result.toArray(new Unit.Value[0]);
	}

	public Unit.Value[] getUnits(String uuid, DateTime at) {
		Organization e = getEntity(uuid);
		if (e == null) throw new UserException("Ingen organisation med UUID: " + uuid);
		
		ArrayList<Unit.Value> result = new ArrayList<Unit.Value>();
        for (UnitRelation.Value v : e.getUnitRelations()) {
        	if (at == null || v.getBitemporal().getValidityInterval().contains(at)) {
        		
        		result.add(v.getChild().getValues().get(at).getValue());
        	}
        }

		return result.toArray(new Unit.Value[0]);
	}

	@Override
	public ObjectRegistration[] getAffectedEntities(String uuid, Interval newInterval) {
		ArrayList<ObjectRegistration> result = new ArrayList<ObjectRegistration>();
		
		Organization org = getEntity(uuid);
		
		// Check rootUnitlocations
		for (RootUnitRelation.Value l : org.getRootUnitRelations()) {
			Interval i = l.getEntity().getValues().get(newInterval.getStart()).getValidityInterval();
			
			// If the unit location does not have interval this can contain new location it is affected
			if (!i.contains(newInterval)) {
				result.add(l.getEntity());
			}
		}
		
		// Check UnitRelations
		for (UnitRelation.Value l : org.getUnitRelations()) {
			Interval i = l.getEntity().getValues().get(newInterval.getStart()).getValidityInterval();
			
			// If the unit location does not have interval this can contain new location it is affected
			if (!i.contains(newInterval)) {
				result.add(l.getEntity());
			}
		}

		return result.toArray(new ObjectRegistration[0]);
	}
}